package logic

import (
	"context"
	"gorm.io/gorm"
	"meituan-waimai/models/mysql"

	"meituan-waimai/meituanrpc/internal/svc"
	"meituan-waimai/meituanrpc/meituanrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ShoppingCardAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewShoppingCardAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ShoppingCardAddLogic {
	return &ShoppingCardAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ShoppingCardAddLogic) ShoppingCardAdd(in *meituanrpc.ShoppingCardAddRequest) (*meituanrpc.ShoppingCardAddResponse, error) {
	// todo: add your logic here and delete this line
	// 查询购物车是否已经存在此商品，存在则累加
	var shoppingCard mysql.ShoppingCard
	mysql.DB.Where("user_id = ? And goods_id = ?", in.UserId, in.GoodsId).First(&shoppingCard)

	// 查询商品价格
	var goods mysql.Goods
	mysql.DB.Where("id = ?", in.GoodsId).First(&goods)

	// 计算总价
	total := float64(in.GoodsNum) * goods.GoodsPrice

	if shoppingCard.ID != 0 {
		// 存在此商品，直接累加
		shoppingCard.GoodsNum = shoppingCard.GoodsNum + int(in.GoodsNum)
		shoppingCard.ShoppingTotal = shoppingCard.ShoppingTotal + total
		mysql.DB.Updates(&shoppingCard)
		return &meituanrpc.ShoppingCardAddResponse{}, nil
	}

	// 加入购物车
	shoppingCard = mysql.ShoppingCard{
		Model:         gorm.Model{},
		UserId:        int(in.UserId),
		GoodsId:       int(in.GoodsId),
		GoodsNum:      int(in.GoodsNum),
		ShoppingTotal: total,
	}
	mysql.DB.Create(&shoppingCard)
	return &meituanrpc.ShoppingCardAddResponse{}, nil
}
